package org.jackysoft.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.HTMLTemplate;
import org.jackysoft.service.AbstractIdentifiedService;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.HTMLTemplateService;
import org.jackysoft.util.IOUtils;
import org.jackysoft.util.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class HTMLTemplateServiceImpl extends AbstractStringIdServiceImpl<HTMLTemplate>
		implements HTMLTemplateService {
     static final Log logger  = LogFactory.getLog(HTMLTemplateServiceImpl.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -272063411418212976L;
	
	public HTMLTemplateServiceImpl() {
		this.type = HTMLTemplate.class;
	}






	@Override
	@Transactional
	public void create(File temp, String fileName)
			throws DataAccessException {
		HTMLTemplate t = new HTMLTemplate();
		try {
			byte[] bs = IOUtils.toByteArray(new FileReader(temp), "GBK");
			t.setData(bs);
			t.setName(StringUtils.splitPreFileName(fileName));
			super.saveOrUpdate(t);
			
		} catch (FileNotFoundException e) {
			logger.error(e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
		
	}



	@Override
	public void update(HTMLTemplate tpl, File temp, String fileName)
			throws DataAccessException, FileNotFoundException, IOException {
		HTMLTemplate t = get(tpl.getId());
		byte[] cont = IOUtils.toByteArray(new FileReader(temp));
		if (t != null) {
			t.setName(StringUtils.splitPreFileName(fileName));
			t.setData(cont);
			super.update(t);
		}

	}	

	@Override
	public void update(String id, String content)
			throws DataAccessException {
		HTMLTemplate tm = get(id);
		tm.setData(content.getBytes());
		update(tm);		
	}
}